package com.example.petstore.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.User;
import com.example.petstore.domain.UserCode;
import com.example.petstore.domain.UserInfo;
import com.example.petstore.mapper.UserCodeMapper;
import com.example.petstore.mapper.UserInfoMapper;
import com.example.petstore.mapper.UserMapper;
import com.example.petstore.util.CryptoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service("userService")
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserCodeMapper userCodeMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    public CommonResponse findUserByUsernameAndPassword(String username, String password) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", CryptoUtil.SHA256(password));
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            return CommonResponse.creatForError("用户名或密码错误");
        }else{
            return CommonResponse.creatForSuccess(user);
        }
    }

    public CommonResponse findUserByGiteeId(String giteeId) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("giteeid", giteeId);
        List<User> userList = userMapper.selectList(query);
        if(userList.size() > 0){
            return CommonResponse.creatForSuccess(userList.get(0));
        }
        return CommonResponse.creatForError("该gitee账号未绑定");
    }
    /*
    * 用户第三方注册后，绑定手机号，创建新用户
    * */
    public CommonResponse saveUserByPhoneNumberAndGitee(String username, String phoneNumber, String giteeId) {
        User user = new User();
        user.setUsername(username);
        user.setPassword("");
        user.setGiteeid(giteeId);
        user.setPhoneNumber(phoneNumber);
        int result = userMapper.insert(user);
        if (result == 1) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("giteeid", giteeId);
//            在UserInfo中也添加信息
            UserInfo userInfo = new UserInfo();
            userInfo.setUsername(username);
            userInfoMapper.insert(userInfo);

            log.info(username + " 注册成功");
            return CommonResponse.creatForSuccess(userMapper.selectOne(queryWrapper));
        }
        log.warn(username + " 注册失败");
        return CommonResponse.creatForError("注册失败");
    }

    public CommonResponse<User> findUserByPhoneNumber(String phoneNumber) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenumber", phoneNumber);
//        User user = userMapper.selectOne(queryWrapper);
        List<User> userList = userMapper.selectList(queryWrapper);
        if(userList.size() != 0){
            return CommonResponse.creatForSuccess(userList.get(0));
        }else{
            return CommonResponse.creatForError("手机号未注册");
        }
    }

    public CommonResponse<User> findUserByUsername(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        System.out.println(username);
//        User user = userMapper.selectOne(userQueryWrapper);
        List<User> user = userMapper.selectList(userQueryWrapper);
        System.out.println(user);
        if(user.size() == 0){
            return CommonResponse.creatForError("用户名不存在");
        }else{
            return CommonResponse.creatForSuccess(user.get(0));
        }
    }

    public CommonResponse saveUserByPhone(String username, String password, String phoneNumber) {
        User user = new User();
        user.setUsername(username);
        password = CryptoUtil.SHA256(password);
        user.setPassword(password);
        user.setPhoneNumber(phoneNumber);
        int result = userMapper.insert(user);
        if(result == 1){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phonenumber", phoneNumber);
            User user1 = userMapper.selectOne(queryWrapper);

            UserInfo userInfo = new UserInfo();
            userInfo.setUsername(username);
            userInfoMapper.insert(userInfo);

            log.info(username + " 注册成功");
            return CommonResponse.creatForSuccess(user1);
        }else{
            log.warn(username + " 注册失败");
            return CommonResponse.creatForError();
        }
    }
    public CommonResponse<User> updateUser(User user) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username", user.getUsername());
        int rowsAffected = userMapper.update(user, updateWrapper);
        if(rowsAffected > 0) {
            return CommonResponse.creatForSuccess(user);//判断是否更新成功
        }
        else {
            return CommonResponse.creatForError();
        }
    }

    public CommonResponse resetPassword(String phoneNumber, String password, String phoneCode) {
//        看手机号是否注册
        CommonResponse commonResponse = findUserByPhoneNumber(phoneNumber);
        if(!commonResponse.isSuccess()){
            return CommonResponse.creatForError("该手机号尚未注册");
        }

//        验证验证码是否正确
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenumber", phoneNumber);
        queryWrapper.eq("type", "reset");
        List<UserCode> userCodes = userCodeMapper.selectList(queryWrapper);
        if(userCodes.size() > 0) {
            if (!userCodes.get(0).getCode().equals(phoneCode)) {
                return CommonResponse.creatForError("验证码错误");
            }
//            超时验证部分
//            LocalDateTime bef = userCodes.get(0).getCreateTime();
//            LocalDateTime current = LocalDateTime.now();
//            Duration dur = Duration.between(bef, current);
//            if(dur.toMinutes() > 10){
//                return CommonResponse.creatForError("验证码已过期");
//            }

            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("phonenumber", phoneNumber);
//
            updateWrapper.set("password", CryptoUtil.SHA256(password));
//            updateWrapper.set("password", password);
            int result = userMapper.update(updateWrapper);
            if (result == 1) {
                log.info(phoneNumber + "密码修改成功");
                return CommonResponse.creatForSuccess("修改成功");
            } else {
                log.warn(phoneNumber + "密码修改失败");
                return CommonResponse.creatForError("修改失败");
            }
        }
        return CommonResponse.creatForError("还未发送验证码");
    }

    public CommonResponse loginByPhone(String phoneNumber, String phoneCode) {
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("phonenumber", phoneNumber);
        User user = userMapper.selectOne(queryWrapper1);

        if(user == null){
            log.warn(phoneNumber + "该手机号未注册");
            return CommonResponse.creatForError("该手机号未注册");
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phonenumber", phoneNumber);
        queryWrapper.eq("type", "login");
        UserCode userCode = userCodeMapper.selectOne(queryWrapper);

        if(userCode == null){
            log.warn("还未发送验证码");
            return CommonResponse.creatForError("还未发送验证码");
        }

        if(userCode.getCode().equals(phoneCode)){
            LocalDateTime localDateTime = LocalDateTime.now();
            LocalDateTime bef = userCode.getCreateTime();
            Duration duration = Duration.between(bef, localDateTime);
//            if(duration.toMinutes() < 10){
                return CommonResponse.creatForSuccess(user);
//            }
//            return CommonResponse.creatForError("验证码已过期");
        }
        log.warn("验证码错误");
        return CommonResponse.creatForError("验证码错误");
    }
    public List<User> getUserList(){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);

        return userList;
    }
    public CommonResponse resetPasswordByUserId(String userId, String newPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userId);
        int res = 0;

        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            user.setPassword(CryptoUtil.SHA256(newPassword));
            res = userMapper.update(user, queryWrapper);
        }
        if (res > 0) {
            return CommonResponse.creatForSuccess();
        } else {
            return CommonResponse.creatForError("更新密码失败！");
        }
    }
}
